package com.example.schoolblog.blog.interceptor;

import com.example.schoolblog.blog.Dto.UserTokenDTO;
import com.example.schoolblog.blog.Mapper.UserMapper;
import com.example.schoolblog.blog.Model.User;
import com.example.schoolblog.blog.Model.UserExample;
import com.example.schoolblog.blog.Service.NotificationService;
import com.example.schoolblog.blog.utils.JWTUtil;
import com.example.schoolblog.blog.utils.RedisService;
import com.example.schoolblog.blog.utils.RedisServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotificationService notificationService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length != 0 ){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("token")){
                    String token = cookie.getValue();
                    UserTokenDTO userTokenDTO =  JWTUtil.parseToken(token);
                    UserExample userExample = new UserExample();
                    userExample.createCriteria().andAccountIdEqualTo(userTokenDTO.getAccountId());
                    List<User> users = userMapper.selectByExampleWithBLOBs(userExample);
                    //判断token是否正确
                    if(userTokenDTO.getAccountId() == null || !(token.equals(users.get(0).getToken()))){
                        break;
                    } else if (users.size() != 0) {
                        //判断token是否需要续期
                        RedisService redisService = new RedisServiceImpl();
                        if(redisService.getExpireTime(users.get(0).getAccountId()) < 1 * 60 * 30){
                            redisService.set(userTokenDTO.getAccountId(), token);
                            log.error("update token info, id is:{}, user info is:{}", userTokenDTO.getAccountId(), token);
                        }
                        //将用户信息渲染到主页
                        request.getSession().setAttribute("user", users.get(0));
                        //获取通知的未读数
                        Long unreadCount = notificationService.unreadCount(users.get(0).getId());
                        request.getSession().setAttribute("unreadCount", unreadCount);
                    }
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
